const routes = require('koa-router')();
const config = require('../../config');
const axios = require('axios');
const qs = require('qs');
var fs = require('fs')
const consola = require('consola');
var images = require("images");

axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded';
axios.defaults.transformRequest = function(data) {
    return qs.stringify(data);
};

// 用户登录
routes.post('/api/login', async function(ctx, next) {
    const { username, password ,randomCode ,logintype, qrcode, ticket, env,smsCode,selSys} = ctx.request.body;
    console.info(`login by type: ${logintype} username: ${username} randomCode: ${randomCode}  password: ${password} qrcode: ${qrcode} ticket: ${ticket} env: ${env} smsCode:${smsCode} selSys:${selSys}`)
    var userip = "";
    try{
        userip =
            ctx.request.headers['x-forwarded-for'] ||
            ctx.request.headers['x-real-ip'] ||
            ctx.request.socket.remoteAddress || 
            ctx.request.connection.socket.remoteAddress;
    }catch(ex){
        console.error("userIpGetFail");
        console.error(ex);
        console.info("headInfo:");
        console.info(ctx.request.headers);
    }
    var apiurl = config.api;
    if(selSys && config["api"+selSys]){
        apiurl = config["api"+selSys]
    }
    var requrl = `${apiurl}/fjtx/user/login`;
    if(username && smsCode){
        requrl = `${apiurl}/fjtx/user/validateSms`;
    }

    await axios
        .post(requrl, {
            userCode: username,
            pwd: password,
            randomCode: randomCode,
            qrcode: qrcode,
            ticket: ticket,
            logintype: logintype,
            ip : userip,
            smsCode: smsCode
        })
        .then(res => {
            console.info("reqinfo:")
            console.info(res.config);
            console.info("respinfo:")
            console.info(res.data);

            if (res.data.code === 200) {
                // 存储 seesion，nuxtServerInit 使用
                if(res.data.data.phone){

                }else{
                    ctx.session.user = res.data.data;
                    ctx.session.env = env;
                    ctx.session.sys = selSys;
                }
            }

            // 返回数据，客户端存储 store
            ctx.body = res.data;
        })
        .catch(err => {
            // TODO: 统一处理 error
            console.error(err);
            ctx.body = {
                code: 404,
                msg: config.api+'fjtx/user/login not work',
                data: null
            };
        });
});

// 用户退出
routes.post('/api/logout', async function(ctx, next) {
    // const javaUrl = urls.logout;

    // const {
    //     guid,
    //     token
    // } = ctx.session.user;

    // // logout(ctx.session);
    // ctx.session = null;
    // clearClientCookies(ctx, ['datacloud-sess', 'datacloud-sess.sig']);

    ctx.session = null;

    ctx.body = {
        data: null,
        msg: 'ok',
        code: 200
    };

    // // 向java后端发送退出请求
    // await axios.post(javaUrl, {
    //         guid,
    //         token
    //     })
    //     .then(res => {
    //         if (res.data) {
    //             const {
    //                 code,
    //             } = res.data;

    //             ctx.body = res.data;
    //         }
    //     })
    //     .catch(err => {
    //         console.log(err);
    //     });
});

// 用户test
routes.get('/api/getStartTime', async function(ctx, next) {
    // console.log('test');
    
    ctx.body = {
        code: 200,
        data: global.startTime
    };
});

routes.get('/img/screenshot.png', async function(ctx, next) {
    // console.log('test');
    const { name} = ctx.request.query;
    // var imgpath = "D:/tmp/screenshot.png";
    var imgpath = "D:/tmp/"+name+".png";
    
    if (!fs.existsSync(imgpath)) {
        ctx.body = {
            data: null,
            msg: 'img no exists path: '+imgpath,
            reqbody:  ctx.request.body,
            code: 200
        };
    }else{
        images(imgpath).size(300).save(imgpath,{quality :100})
        var body = fs.readFileSync(imgpath)
        ctx.status = 200;
        ctx.type = "png";
        ctx.length = Buffer.byteLength(body);
        ctx.body = body;
    }
});

module.exports = routes;
